package org.algorithm.Sort;

import java.util.Arrays;

public class MergeSort2 {

    public static void mergeSort(int[] arr) {

        int n = arr.length;

        int[] helper = new int[n];
        split(arr, 0, n - 1, helper);
    }

//    private static void split(int[] a1, int left, int right, int[] helper) {
//        if (left == right) {
//            return;
//        }
//
//        int mid = (left + right) >>> 1;
//        split(a1, left, mid, helper);
//        split(a1, mid + 1, right, helper);
//
//        merge(a1, left, mid, mid + 1, right, helper);
//
//        System.arraycopy(helper, left, a1, left, right - left + 1);
//
//    }

    private static void merge(int[] a1, int i, int iEnd, int j, int jEnd, int[] helper) {

        int current = i;

        while (i <= iEnd && j <= jEnd) {
            if (a1[i] < a1[j]) {
                helper[current] = a1[i];
                i++;
            } else {
                helper[current] = a1[j];
                j++;
            }
            current++;
        }

        //如果左侧的数组提前遍历完，将右侧的数组剩下的数据直接拷贝到辅助数组中
        if (i > iEnd) {
            //jEnd-j+1：j表示右侧数组没有遍历的左边界，jEnd表示右侧数组的右边界
            System.arraycopy(a1, j, helper, current, jEnd - j + 1);
        }

        if (j > jEnd) {
            System.arraycopy(a1, i, helper, current, iEnd - i + 1);
        }

    }


    public static void main(String[] args) {
        int[] array = {12, 11, 13, 5, 6, 7};
        mergeSort(array);

        System.out.println("Sorted array:");
        for (int i : array) {
            System.out.print(i + " ");
        }
    }


    public static void split(int[] array, int left, int right, int[] helper) {
        if (left < right) {
            int mid = (left + right) >>> 1;
            split(array, left, mid, helper);
            split(array, mid + 1, right, helper);
            merge(array, left, mid, right, helper);
        }
    }

    public static void merge(int[] array, int start, int mid, int end, int[] helper) {
        int currIndex = start;

        int leftIndex = start;
        int rightIndex = mid + 1;

        while (leftIndex <= mid && rightIndex <= end) {
            if (array[leftIndex]<array[rightIndex]){
                helper[currIndex]=array[leftIndex];
                leftIndex++;
            }else {
                helper[currIndex]=array[rightIndex];
                rightIndex++;
            }
            currIndex++;
        }

        while (leftIndex<=mid){
            helper[currIndex]=array[leftIndex];
            currIndex++;
            leftIndex++;
        }

        while (rightIndex<=end){
            helper[currIndex]=array[rightIndex];
            currIndex++;
            rightIndex++;
        }

        for (int i = start; i <=end; i++) {
            array[i]=helper[i];
        }

    }

}
